package com.wen.order.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wen.commonutils.GuLiUtils;
import com.wen.commonutils.ResultEntity;
import com.wen.order.entity.TOrder;
import com.wen.order.service.TOrderService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author wen
 * @since 2021-06-19
 */
@RestController
@RequestMapping("/edu/order/service")
public class TOrderController {
    @Resource
    private TOrderService orderService;

    /**
     * 根据课程id创建订单
     *
     * @param courseId 课程id
     * @param request  含有token的请求
     * @return 订单号
     */
    @PostMapping("createOrder/{courseId}")
    public ResultEntity creatOrder(@PathVariable("courseId") String courseId, HttpServletRequest request) {
        String memberId = GuLiUtils.getMemberIdByJwtToken(request);
        if (StringUtils.isEmpty(memberId)) return ResultEntity.error().message("请登录后再购买");
//        创建订单，返回订单号
        String orderNo = orderService.createOrder(courseId, memberId);
        return ResultEntity.ok().data("orderNo", orderNo);
    }

    /**
     * 根据订单号查询订单信息
     *
     * @param orderNo 订单号
     * @return 订单信息
     */
    @GetMapping("getOrderInfo/{orderNo}")
    public ResultEntity getOrderInfo(@PathVariable("orderNo") String orderNo) {
        QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no", orderNo);
        TOrder order = orderService.getOne(wrapper);
        return ResultEntity.ok().data("order", order);
    }

    /**
     * 根据课程id和用户id查询当前课程是否被购买
     *
     * @param memberId 用户id
     * @param courseId 课程id
     * @return true(已经被当用户购买) or false(当前用户未购买)
     */
    @GetMapping("isBuyCourse/{memberId}/{courseId}")
    public boolean isBuyCourse(@PathVariable("memberId") String memberId, @PathVariable("courseId") String courseId) {
        //订单状态是1表示支付成功
        int count = orderService.count(new QueryWrapper<TOrder>().eq("member_id", memberId).eq("course_id", courseId).eq("status", 1));
        return count == 1;
    }
}

